package com.xzt.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzt.bookstore.dto.BookCreateRequest;
import com.xzt.bookstore.entity.Book;
import com.xzt.bookstore.mapper.BookMapper;
import com.xzt.bookstore.service.BookService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 图书服务实现类
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    
    @Override
    public Page<Book> getBookList(Long current, Long size, String name, String author, String category, Integer status) {
        Page<Book> page = new Page<>(current, size);
        
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        
        // 图书名称模糊查询
        if (StringUtils.hasText(name)) {
            wrapper.like(Book::getName, name);
        }
        
        // 作者模糊查询
        if (StringUtils.hasText(author)) {
            wrapper.like(Book::getAuthor, author);
        }
        
        // 分类精确查询
        if (StringUtils.hasText(category)) {
            wrapper.eq(Book::getCategory, category);
        }
        
        // 状态查询
        if (status != null) {
            wrapper.eq(Book::getStatus, status);
        }
        
        // 按创建时间倒序排列
        wrapper.orderByDesc(Book::getCreateTime);
        
        return this.page(page, wrapper);
    }
    
    @Override
    public Book createBook(BookCreateRequest request) {
        // 创建图书对象
        Book book = new Book();
        book.setName(request.getName());
        book.setAuthor(request.getAuthor());
        book.setIsbn(request.getIsbn());
        book.setPrice(request.getPrice());
        book.setStock(request.getStock());
        book.setDescription(request.getDescription());
        book.setCategory(request.getCategory());
        book.setPublisher(request.getPublisher());
        book.setPublishDate(request.getPublishDate());
        book.setStatus(request.getStatus() != null ? request.getStatus() : 1); // 默认为在售
        
        // 保存到数据库
        this.save(book);
        
        return book;
    }
    
    @Override
    public Book offlineBook(Long id) {
        // 查询图书
        Book book = this.getById(id);
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        
        // 检查是否已经下架
        if (book.getStatus() == 0) {
            throw new RuntimeException("图书已经下架");
        }
        
        // 更新状态为下架
        book.setStatus(0);
        this.updateById(book);
        
        return book;
    }
}

